package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC748 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String shortestCompletingWord(String licensePlate, String[] words) {
            Map<Character, Integer> cnt = new HashMap<>();
            for (int i = 0; i < licensePlate.length(); i++) {
                if (Character.isAlphabetic(licensePlate.charAt(i))) {
                    char cur = licensePlate.substring(i, i + 1).toLowerCase().charAt(0);
                    cnt.put(cur, cnt.getOrDefault(cur, 0) + 1);
                }
            }

            String res = null;
            for (String word : words) {
                Map<Character, Integer> curCnt = deepCopyMap(cnt);
                for (int i = 0; i < word.length(); i++) {
                    if (curCnt.isEmpty()) break;
                    if (!curCnt.containsKey(word.charAt(i))) continue;
                    if (curCnt.get(word.charAt(i)) <= 1) curCnt.remove(word.charAt(i));
                    else curCnt.put(word.charAt(i), curCnt.get(word.charAt(i)) - 1);
                }

                if (curCnt.isEmpty()) {
                    if (null == res || res.length() > word.length()) res = word;
                }
            }

            return res;
        }

        public Map<Character, Integer> deepCopyMap(Map<Character, Integer> cnt) {
            Map<Character, Integer> copy = new HashMap<>();
            for (Character ch : cnt.keySet()) {
                copy.put(ch, cnt.get(ch));
            }
            return copy;
        }
    }

    public void run() {
        Solution solution = new Solution();

//        输入：licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
//        输出："pest"
//        解释：licensePlate 只包含字母 "s" 。所有的单词都包含字母 "s" ，其中 "pest"、"stew"、和 "show" 三者最短。答案是 "pest" ，因为它是三个单词中在 words 里最靠前的那个。
        String[] arr = {"looks", "pest", "stew", "show"};
        System.out.println(solution.shortestCompletingWord("1s3 456", arr));
    }

    public static void main(String[] args) throws Exception {
        LC748 an = new LC748();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
